<?php
	session_start();
	
	require_once('config.php');
	
	if($_SESSION['logged'] && $_SESSION['username'] == USERNAME && $_SESSION['password'] == PASSWORD)
	{	
?>
<!DOCTYPE html>
<html>
	<head>
		<?php
			require_once('scripts/head_tags.php');
		?>
		<link rel="stylesheet" href="resources/css/jquery-ui.css" />
		<script src="resources/js/jquery-1.8.3.js"></script>
		<script src="resources/js/jquery-ui.js"></script>
		<script>
		  $(function() {
			$( "#date_time" ).datepicker();
		  });
		  
		  function deleteHistory()
			{
				var selected_day = $("#selected_day").val();
				
				var request = $.ajax({
					type: "POST",
					url: "delete_history.php",
					data: { day : selected_day }
				});
				
				request.done(function(msg) {
					$("#list").fadeOut("slow")
					$("#result").html(msg);
				});
			}
		</script>
	</head>
	<body>
		<h1>
			<img src="resources/images/alarm.png" alt="icon" /> Easy Security 
		</h1>
		<section id="submit_form">
			<form action="<?php echo $_SERVER['PHP_SELF']; ?>?action=select" method="post">
				<label for="date_time">
					Select date:
				</label>
				<input type="text" name="date_time" id="date_time" />
				<input type="submit" value="Select >" />
				<p id="hint">
					Example of the date format : mm/dd/yyyy
				</p>
			</form>
		</section>
		<?php
			$action = $_GET['action'];
			
			if($action == 'select')
			{
				if(isset($_POST['date_time']))
				{
					$date = $_POST['date_time'];
					
					$date_exploded = explode("/", $date);

					$month = $date_exploded[0];
					
					$day = $date_exploded[1];
					
					$year = $date_exploded[2];
						
					if(is_numeric($month) && is_numeric($day) && is_numeric($year))
					{
						if(checkdate($month, $day, $year))
						{
							$selected_day = strtotime($date);
							
							$next_day = $selected_day + (24*3600);
							
							$connect = new DbConnector();
							
							$select = $connect->query("SELECT * FROM ".$TABLES['detection']." WHERE unix_time >= ".$selected_day." && unix_time <= ".$next_day."");
							
							if($connect->numRows($select))
							{
								echo '<div id="list">';
								
									while($row = $connect->fetchObject($select))
									{
										echo $row->date_time.'<br />';
									}
									
								echo '</div>';
								
								echo '<input type="hidden" name="selected_day" id="selected_day" value="'.$selected_day.'" />';
								
								echo '<div id="result"></div>';
								
								echo '<a href="#" onclick="deleteHistory()">~Delete history~</a><br /><hr />';
							}
							else 
							{
								echo 'No motion has been detected during that day!<br /><br />';
							}
						}
					}
				}
			}
			else
			{
				echo '<br />';
			}
			
			require_once('scripts/footer.php');
		?>
	</body>
</html>
<?php
	}
	else
	{
		header('Location: '.INDEX.'');
	}
?>